package cn.xinfei.xdecision.manager.controller.data;


import cn.xinfei.xdecision.common.model.common.ResponseEntityBuilder;
import cn.xinfei.xdecision.common.model.common.ResponseEntityDto;
import cn.xinfei.xdecision.common.model.component.scriptrule.RuleMixExpressionCheck;
import cn.xinfei.xdecision.common.model.component.scriptrule.RuleMixExpressionCheckResult;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataException;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataExceptionType;
import cn.xinfei.xdecision.common.service.component.scriptrule.RuleScriptVersionService;
import cn.xinfei.xdecision.data.core.frame.executors.groovy.check.ExpressionService;
import cn.xinfei.xdecision.data.core.vo.groovy.MixExpressionCheck;
import cn.xinfei.xdecision.data.core.vo.groovy.MixExpressionCheckResult;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static com.google.common.base.Preconditions.checkState;

@Controller
@RequestMapping("datamanage/derive")
@ResponseBody
public class ScriptCheckController {

    @Autowired
    private ExpressionService expressionService;

    @Resource
    private RuleScriptVersionService ruleScriptVersionService;


    @ApiOperation(value = "测试脚本")
    @PostMapping("expression/test")
    public ResponseEntityDto<Object> testExpressionPost(HttpServletRequest request, @RequestBody MixExpressionCheck mixExpressionCheck) {
        List<MixExpressionCheckResult> checkResults = expressionService.check(mixExpressionCheck);
        HashMap<String, Object> executorResult = new HashMap<>();
        executorResult.put("testResults", checkResults);
        return ResponseEntityBuilder.buildNormalResponse(executorResult);
    }

    @ApiOperation(value = "测试脚本规则")
    @PostMapping("expression/testRule")
    public ResponseEntityDto<Object> testRuleExpressionPost(@RequestBody RuleMixExpressionCheck mixExpressionCheck) {
        List<RuleMixExpressionCheckResult> checkResults = ruleScriptVersionService.scriptRulecheck(mixExpressionCheck);
        HashMap<String, Object> executorResult = new HashMap<>();
        executorResult.put("testResults", checkResults);
        return ResponseEntityBuilder.buildNormalResponse(executorResult);
    }


    @ApiOperation(value = "下载模版")
    @GetMapping("expression/downloadTemplate")
    public void getTemplate(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        checkState(StringUtils.isNotEmpty(id), "id为空！");

        String expressionUrl = request.getParameter("expression");
        checkState(StringUtils.isNotEmpty(expressionUrl), "expression为空！");
        String varCodes = request.getParameter("varCodes");
        checkState(StringUtils.isNotEmpty(varCodes), "varCodes为空！！");

        String expression = null;
        String varCodesDecode;
        try {
            expression = URLDecoder.decode(expressionUrl, "UTF-8");
            varCodesDecode = URLDecoder.decode(varCodes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new XDecisionDataException(
                    XDecisionDataExceptionType.EXPRESSION_ERROR,
                    "expression decode error!", e
            );
        }
        String expressionResultType = request.getParameter("expressionResultType");

        try {
            expressionService.getTemplate(response, id, expression, expressionResultType, Arrays.asList(varCodesDecode.split(",")));
        } catch (Exception e) {
            throw new XDecisionDataException(
                    XDecisionDataExceptionType.TEMPLATE_DOWNLOAD_ERROR_CODE,
                    "模版文件下载异常!", e
            );
        }
    }

    @ApiOperation(value = "文件批量校验")
    @PostMapping("expression/testExpressionFromFile")
    public void testExpressionFromFile(HttpServletResponse response, @RequestParam("file") MultipartFile file, @RequestParam("id") String id) {
        try {
            expressionService.batchCheck(response, id, file);
        } catch (Exception e) {
            throw new XDecisionDataException(
                    XDecisionDataExceptionType.TEMPLATE_DOWNLOAD_ERROR_CODE,
                    "批量校验异常!", e
            );
        }
    }
}
